import Vue from 'vue'
import VueRouter from 'vue-router'

import login from "@/views/user/login.vue"
import home from "@/views/home/home.vue"
import search from "@/views/home/search.vue"
import searchResult from "@/views/home/searchResult.vue"

import myarticle from "@/views/home/article.vue"
import movie from "@/views/movie/movie.vue"

import qa from "@/views/qa/qa.vue"
import user from "@/views/user/user.vue"
import student from "@/views/user/student.vue"


import edit from "@/views/user/edit.vue"
import layout from "@/views/layout.vue"
import notfound from "@/views/notfound/notfound.vue"

import { getToken } from "@/utils/token.js"

// 在js文件中需要重新导入组件
import { Toast } from 'vant';


Vue.use(VueRouter)

const routes = [
  {
    path: "/searchResult",
    name: "searchResult",
    component: searchResult
  },
  {
    path: "/student",
    name: "student",
    component: student
  },
  {
    path: "/login",
    name: "login",
    component: login
  },
  {
    path: "/myarticle",
    name: "myarticle",
    component: myarticle
  },
  {
    path: "/search",
    name: "search",
    component: search
  },
  {
    path: "/",
    name: "layout",
    component: layout,
    children: [
      {
        path: "/home",
        name: "home",
        component: home
      },
      {
        path: "/movie",
        name: "movie",
        component: movie
      },
      {
        path: "/qa",
        name: "qa",
        component: qa
      },
      {
        path: "/user",
        name: "user",
        component: user,
        meta: {
          isLogin: true
        }
      },
      {
        path: '/',
        redirect: '/home'
      }
    ]
  },
  {
    path: "/edit",
    name: "edit",
    component: edit
  },
  {
    path: "/notfound",
    name: "notfound",
    component: notfound
  },
  {
    // 任意路径重定向notfound
    // 路由默认从上往下匹配，如果可以匹配到则跳转页面，
    // 无法匹配则继续往下匹配，直到所有路由匹配结束
    path: "*",
    redirect: "/notfound"
  }
]

const router = new VueRouter({
  routes
})

// 路由导航卫士
router.beforeEach((to, from, next) => {
  // console.log(to);
  // console.log(from);
  // next()

  if (to.meta.isLogin) {
    if (getToken()) {
      next()
    } else {
      Toast.fail('请先登入');
      next("/login")
    }
  } else {
    next()
  }
})

export default router
